<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="locaArtList">筛选</el-button>
            <el-button type="info" size="small" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubVisible = true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
        <el-table
            :data="artList"
            stripe
            style="width: 100%"
            border
            >
            <el-table-column
              prop="title"
              label="文章标题"
              >
              <template v-slot="{row}">
                <el-link type="primary" :underline="false" @click="showDetail(row.id)">{{row.title}}</el-link>
              </template>
            </el-table-column>
            <el-table-column
              prop="cate_name"
              label="文章分类"
              >
            </el-table-column>
            <el-table-column
              label="发表时间">
              <template v-slot="{row}">
                {{FormData(row.pub_date)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="state"
              label="状态"
              >
            </el-table-column>
              <el-table-column
              prop="state"
              label="操作"
              >
              <template v-slot="{row}">
                <el-button type="danger" size="mini" @click="remove(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
      <!-- 分页区域 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="q.pagenum"
          :page-sizes="[2, 3, 5, 20]"
          :page-size="q.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      <el-dialog
        title="提示"
        :visible.sync="pubVisible"
        width="30%"
        :before-close="handleClose"
        fullscreen
        @closed="ced">
        <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
              <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章内容" prop="content">
            <quill-editor v-model="pubForm.content" @blur="$refs.pubFormRef.validateField('content')"></quill-editor>
          </el-form-item>
          <el-form-item label="文章封面" prop="cover_img">
          <!-- 用来显示封面的图片 -->
          <img v-if="preview" :src="preview" alt="" class="cover-img" ref="imgRef"/>
          <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef"/>
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none;" accept="image/*" ref="iptFile" @change="hImgChange"/>
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFile.click()">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item prop="state">
          <el-button type="primary" @click="hPub('已发布')">发布</el-button>
          <el-button type="info" @click="hPub('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
      </el-dialog>
      <!-- 展示文章详情对话框 -->
      <el-dialog
        title="文章预览"
        :visible.sync="deatilVisible"
        width="80%"
        >
        <h1 class="title">{{ atrDetail.title }}</h1>

        <div class="info">
          <span>作者：{{ atrDetail.nickname || atrDetail.username }}</span>
          <span>发布时间：{{ FormData(atrDetail.pub_date) }}</span>
          <span>所属分类：{{ atrDetail.cate_name }}</span>
          <span>状态：{{ atrDetail.state }}</span>
        </div>

  <!-- 分割线 -->
          <el-divider></el-divider>

          <img :src="'http://www.liulongbin.top:3008' + atrDetail.cover_img" alt="" />

          <div v-html="atrDetail.content"></div>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data() {
    return {
      deatilVisible: false,
      // 保存详情页的数据
      atrDetail: {},
      total: 0,
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      pubVisible: false,

      // 表单的数据对象
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        state: '',
        cover_img: ''
      },
      // 表单的验证规则对象
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'change' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
        cover_img: [{ required: true, message: '请选择文章封面', trigger: 'blur' }]
      },
      cateList: [],
      artList: [],
      preview: ''
    }
  },
  created() {
    this.locaCateList()
    this.locaArtList()
  },
  methods: {
    // 删除数据
    remove(id) {
      this.$confirm('此操作将永久删除该文文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const { data: res } = await this.$http.delete('/my/article/info', { params: { id } })
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)

        // this.deatilVisible = false
        // 判断页面中的数据只有一遍且pegenum>1
        if (this.artList.length === 1 && this.q.pagenum > 1) {
          this.q.pagenum--
        }
        this.locaArtList()
      }).catch(() => {

      })
    },
    // 展示详情页的数据
    async showDetail(id) {
      const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
      if (res.code !== 0) return this.$message.error(res.message)
      // this.$message.success(res.message)
      this.atrDetail = res.data
      this.deatilVisible = true
    },
    resetForm() {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.locaArtList()
    },
    // 当每一页条数进行切换时触发
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.q.pagesize = val
      this.q.pagenum = 1
      this.locaArtList()
    },
    // 当前页进行切换时触发
    handleCurrentChange(val) {
      // 重新发送请求 q
      this.q.pagenum = val
      // console.log(`当前页: ${val}`)
      this.locaArtList()
    },
    handleClose(done) {
      this.$confirm('确认关闭？', '提示', {
        type: 'warning'
      })
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    async locaCateList() {
      const { data: res } = await this.$http.get('/my/cate/list')
      this.cateList = res.data
    },
    hImgChange(e) {
      const file = e.target.files[0]
      if (file) {
        // 设置表单数据
        this.pubForm.cover_img = file
        // 设置预览图片
        // 核心: 将图片转成 img 的 src 可支持的模式
        this.preview = URL.createObjectURL(file)
        this.$refs.pubFormRef.validateField('cover_img')
      } else {
        this.$refs.iptFile.value = ''
        this.pubForm.cover_img = ''
        this.preview = ''
      }
    },
    hPub(state) {
      this.pubForm.state = state
      this.$refs.pubFormRef.validate(async valid => {
        if (!valid) return
        // 发送请求
        // http 协议: 超文本传输协议
        // 在 http 协议下传输数据只支持两种格式: 文本 / 二进制
        // 由于互联网上传输的数据类型非常非常多
        const fd = new FormData()
        for (const k in this.pubForm) {
          fd.append(k, this.pubForm[k])
        }
        // Object.keys(this.pubForm).forEach(k => fd.append(k, this.pubForm[k])
        // 如果传入的就是Form data 对象, axios会自动设置 Content-type 为: multipart/form-data
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 关闭弹出框
        this.pubVisible = false

        // 清空表单
        this.$refs.pubFormRef.resetFields()
        this.preview = ''
        this.locaArtList()
      })
    },
    async locaArtList() {
      // 发情求
      const { data: res } = await this.$http.get('/my/article/list', { params: this.q })
      this.artList = res.data
      this.total = res.total
    },
    FormData(date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    ced() {
      this.$refs.pubFormRef.resetFields()
      this.$refs.iptFile.value = ''
      this.pubForm.cover_img = ''
      this.preview = ''
    }
  }
}
</script>

<style lang="less" scoped>
// scoped
// 1. 给当前组件内 template 中所有的标签上 data-v-hash
// 2. 给当前style 中所有的选择器加上属性交际选择器
// 注意事项: 如果是组件则会给根标签加 data-v-hash
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 不能给父盒子设置高度, 子盒子使用的高度是100% 会导致错位
// 将属性交际选择器变成属性后代选择器
/deep/ .ql-editor{
  height: 300px !important;

}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>
